//
//  XJEmojiKeyboard.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/27.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

class XJEmojiKeyboard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 布局界面,添加控件
    private func setupUI() {
        
        //点击keyboardToolBar实现联动
        emojiToolBar.emotionBtnClickClosure = { (type)->() in
            
            let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
            self.emojiCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            self.showPageControl(indexPath)
        
        }
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(emojiToolBar)
        addSubview(emojiCollectionView)
        addSubview(pageControl)
        
        emojiToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self)
            make.height.equalTo(37)
        }
        pageControl.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(emojiToolBar.snp_top)
            make.centerX.equalTo(emojiToolBar)
        }
        emojiCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.leading.trailing.equalTo(self)
            make.bottom.equalTo(emojiToolBar.snp_top)
        }
        
        /**
        *  滚到默认表情,需要在界面加载完成后再移动
        */
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.emojiCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            self.emojiToolBar.selectSection = indexPath.section
            
            self.showPageControl(indexPath)
        }
    }
    // MARK: - 子控件frame
    override func layoutSubviews() {
        
        super.layoutSubviews()
       
        let layout = emojiCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: SCREENW, height: self.frame.height - emojiToolBar.frame.height)
    }
    
    // MARK: - 懒加载控件
    
    private lazy var pageControl: UIPageControl = {
    
        let pageVC = UIPageControl()
        //key通过运行时获得
        pageVC.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageVC.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        
        pageVC.userInteractionEnabled = false
        
        return pageVC
    }()
    
    private lazy var emojiToolBar: XJEmojiViewToolBar = XJEmojiViewToolBar(frame:CGRectZero)
    
    private lazy var emojiCollectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
    
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionView.pagingEnabled = true
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.registerClass(XJEmojiPageCell.self, forCellWithReuseIdentifier: "emojiCell")
        
        return collectionView
    }()
}

// MARK: - UICollectionViewDataSource
extension XJEmojiKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return XJEmojiKeyboardViewModel.sharedEmojiViewModel.allEmotions.count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return XJEmojiKeyboardViewModel.sharedEmojiViewModel.allEmotions[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("emojiCell", forIndexPath: indexPath) as! XJEmojiPageCell
        
        cell.indexPath = indexPath
        cell.emotions = XJEmojiKeyboardViewModel.sharedEmojiViewModel.allEmotions[indexPath.section][indexPath.item]
        
        return cell
    }
    
    /**
     监听collectionView滚动
     */
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        var center = scrollView.center
        center.x = center.x + scrollView.contentOffset.x
        
        //当前显示的cell
        let cells = emojiCollectionView.visibleCells()
        
         // 目的：取到 CollectionView 当前显示的多的cell的 IndexPath的section
        let indexPath: NSIndexPath
        
        if cells.count == 2 {
        
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            //取到显示得多的那个cell的indexPath
            //判断第一个cell的范围是否包含当前计算出来的center
            if CGRectContainsPoint(firstCell.frame, center){
                
                indexPath = emojiCollectionView.indexPathForCell(firstCell)!
            }else{
                indexPath = emojiCollectionView.indexPathForCell(lastCell)!
                
            }
            
        }else{
        
            indexPath = emojiCollectionView.indexPathForCell(cells.first!)!
        }
            // print(indexPath.section)
            emojiToolBar.selectSection = indexPath.section
            showPageControl(indexPath)
    }
    
    private func showPageControl(indexPath: NSIndexPath) {
    
    pageControl.numberOfPages = XJEmojiKeyboardViewModel.sharedEmojiViewModel.allEmotions[indexPath.section].count
        pageControl.currentPage = indexPath.item
        
        //最近表情,不显示pagecontrol
        pageControl.hidden = indexPath.section == 0
    }
}
